package cn.itsource.page.service.impl;

import cn.itsource.feignclient.FastdfsFeignClientt;
import cn.itsource.feignclient.FeignClientt;
import cn.itsource.page.domain.Pager;
import cn.itsource.page.mapper.PagerMapper;
import cn.itsource.page.mapper.SiteMapper;
import cn.itsource.page.service.IPagerService;
import cn.itsource.page.util.VelocityUtils;
import cn.itsource.util.AjaxResult;
import cn.itsource.util.ZipUtils;
import cn.itsource.util.createfile.CreateFile;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import net.bytebuddy.implementation.bytecode.Throw;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.itsource.hrm.mq.Mq.EXCHANGE_NAME;
import static cn.itsource.hrm.path.FileExtension.FILE_HTML;
import static cn.itsource.hrm.path.FileExtension.FILE_VM;
import static cn.itsource.hrm.path.FileExtension.FILE_ZIP;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zd
 * @since 2020-02-29
 */
@Service
public class PagerServiceImpl extends ServiceImpl<PagerMapper, Pager> implements IPagerService {
    @Autowired
    private FastdfsFeignClientt fastdfsFeignClientt;
    @Autowired
    private FeignClientt feignClientt;
    @Autowired

    private RabbitTemplate rabbitTemplate;
    @Autowired
    private SiteMapper siteMapper;
    //获得操作系统临时文件夹，临时文件的目录会跟随操作系统，就不用担心/ 和\的问题
    // C:\Users\asus-pc\AppData\Local\Temp\
    private String getTempPath() {
        String tempPath = System.getProperty("java.io.tmpdir");
        return tempPath;
    }


    //页面静态化
    @Override
    public void pageStatic(String redisKey, String pagerName) throws Exception {
        //首先对传入的字段进行判断
        if (new String(redisKey).length() == 0 || new String(pagerName).length() == 0) {
            System.out.println("TODO+3");
            //TODO+3
            throw new RuntimeException("字段非法异常");
        }
        //根据pagerName查询fastdfs中模板的地址
        Pager pager = baseMapper.selectByName(pagerName);
        //下载路径
        String url = pager.getTemplateUrl();
        //根据下载路径从fastdfs上面下载模板
        //调用fastdfs去下载模板（下载下来是一个zip）
        byte[] templateZip = fastdfsFeignClientt.download(url);
        //判断文件是否下载下来
        if (templateZip.length == 0 || templateZip == null) {
            System.out.println("TODO+2");//TODO+2
            throw new RuntimeException("文件下载失败");

        }
        //在操作系统中创建一个临时文件
        String filePath = getTempPath() + redisKey + FILE_ZIP;
        //判断文件是否存在，不存在就创建
        File file = CreateFile.Create(filePath);
        //复制文件的小工具，将下载的文件写入到磁盘

            FileCopyUtils.copy(templateZip, file);

        //解压文件路劲
       String unzipPath= getTempPath()+"pagestatic/";
        //解压文件
        try {
            ZipUtils.unZip(filePath,unzipPath);
        } catch (Exception e) {
            System.out.println("TODO+PagerServiceImpl+1"); //TODO+PagerServiceImpl+1
            e.printStackTrace();
        }
        //从redis中查询数据
        AjaxResult redisResult = feignClientt.get(redisKey);
        Map<String,Object> model = JSON.parseObject(redisResult.getResultObj().toString(), Map.class);
        //封装数据 staticRoot：解压文件的路径   courseTypes：数据

        //($firstType in  $model.courseTypes)
        //set ($template=$model.staticRoot+"template/common-link.vm")
        model.put("staticRoot",unzipPath);
        //home.vm文件的名字约定，在前端保存数据的时候，存入的引文名字就是解压文件里面的home.vm的名字
        String templateFilePathAndName=unzipPath+pagerName+FILE_VM;
        //文件在临时目录中输出的路径
       String targetFilePathAndName=unzipPath+pagerName+FILE_HTML;
       //判断磁盘有没有该文件
        File file1 = CreateFile.Create(targetFilePathAndName);
        // model.put("course_type",redisResult.getResultObj())
        //合并模板 staticByTemplate(Object model, String templateFilePathAndName, String targetFilePathAndName)
        VelocityUtils.staticByTemplate(model,unzipPath,targetFilePathAndName);
        //将生成的html文件上传到fastdfs上面

            AjaxResult ajaxResult = fastdfsFeignClientt.uploadFile(FileCopyUtils.copyToByteArray(file1), "html");
            if (!ajaxResult.isSuccess()||ajaxResult.getResultObj()==null) {
                throw new RuntimeException("文件上传失败");
            }
            String fastdfsPath = ajaxResult.getResultObj().toString();

        //messaage  包含：物理路径和下载路径fastdfsPath

        String physicalPath = pager.getPhysicalPath();//物理路径
//打包消息
        Map<String,String> messaage =new HashMap<>();
        messaage.put("physicalPath",physicalPath);
        messaage.put("fastdfsPath",fastdfsPath);
        //site里面的sn就是rutingkey
        Long siteId = pager.getSiteId();
        String sn = siteMapper.selectById(siteId).getSn();
        //向mq发消息
        rabbitTemplate.convertAndSend(EXCHANGE_NAME,sn,JSON.toJSONString(messaage));
    }
}
